package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Set;

/**
 * 设备数据导入Service业务层处理
 *
 * @author xjl
 * @date 2025-10-19
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备数据导入
     *
     * @param id 设备数据导入主键
     * @return 设备数据导入
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据导入列表
     *
     * @param deviceData 设备数据导入
     * @return 设备数据导入
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据导入
     *
     * @param deviceData 设备数据导入
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据导入
     *
     * @param deviceData 设备数据导入
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据导入
     *
     * @param ids 需要删除的设备数据导入主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据导入信息
     *
     * @param id 设备数据导入主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void addDeviceData(String contentStr) {
        //判断字符串是否为空
        if (contentStr == null) {
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
//根据设备Id查找Iot
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        String iotId = jsonObject.getByPath("notify_data.header.device_id", String.class);
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(queryWrapper);
        if (device == null) {
            return;
        }
        JSONObject properties = (JSONObject) jsonObject.getByPath("notify_data.body.services[0].properties");
        Set<String> keySet = properties.keySet();
        String eventTimeStr = jsonObject.get("event_time", String.class);
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);
        List<DeviceData> list = new ArrayList<>();
        for (String key : keySet) {
            Object value = properties.get(key);
            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
            deviceData.setId(null);
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setFunctionId(key);
            deviceData.setDataValue(value.toString());
            deviceData.setAlarmTime(eventTime);
            list.add(deviceData);
        }
        try {
            this.saveBatch(list);
            redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).put(iotId,JSONUtil.toJsonStr(list));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cleanDate(Integer minute) {
        Long id = deviceDataMapper.selectMinter(minute);
        deviceDataMapper.add(id);
        deviceDataMapper.deleteOld(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void selete() {
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(DeviceData::getAlarmTime, LocalDateTime.now().minusMinutes(2));
        List<DeviceData> list = deviceDataMapper.selectList(queryWrapper);
        for (DeviceData deviceData : list) {
            System.out.println(deviceData);
            deviceDataMapper.addHistory(deviceData);
            Long id = deviceData.getId();
            deviceDataMapper.deleteById(id);
        }

    }


}
